#include <time.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/select.h>
// ============== 说明 ==============
// 已完成：Get/2 读取日志
// 下一步：读代码，截取关键信息
// ============== 宏定义 ==============
#define PORT            9080
#define BUF_SIZE        4096
#define MAX_CLIENTS     10
#define LOG_FILE        "receive_massages.log"

// ============== 宏函数 ==============
#define CHECK_ERROR(cond, msg, cleanup) \
    if(cond) { perror(msg); cleanup; return -1; }

// ============== 函数声明 ==============
int send_http_response(int fd, const char* content_type, const char *content);
int get_device_id_from_request(const char *http_request);
int send_log(int client_fd);
int clear_log(int client_fd);

// ============== 主函数 ==============
int main() {
    // 检查句柄返回
    int ret_check = 0;

    // 创建socket
    int socket_fd = socket(AF_INET, SOCK_STREAM, 0);
    CHECK_ERROR(socket_fd < 0, "socket", NULL);

    // 设置端口复用
    int reuse = 1;
    ret_check = setsockopt(socket_fd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse));
    CHECK_ERROR(ret_check < 0, "setsockopt", close(socket_fd));

    // 绑定地址
    struct sockaddr_in addr = {
        .sin_family = AF_INET,
        .sin_port = htons(PORT),
        .sin_addr.s_addr = INADDR_ANY
    };

    ret_check = bind(socket_fd, (struct sockaddr*)&addr, sizeof(addr));
    CHECK_ERROR(ret_check < 0, "bind", close(socket_fd));

    // 开始监听
    ret_check = listen(socket_fd, MAX_CLIENTS);  // [!] 使用宏定义
    CHECK_ERROR(ret_check < 0, "listen", close(socket_fd));

    printf("Server started on port %d\n", PORT);

    // 创建监听队列
    int client_fds[MAX_CLIENTS] = {0};
    int n_clients = 0;

    // base_set，保存下一次循环要监听的文件描述符集合
    fd_set base_set;
    FD_ZERO(&base_set);
    FD_SET(socket_fd, &base_set);
    FD_SET(STDIN_FILENO, &base_set);

    while (1) {
        // 1. 准备工作：更新下标 | 监听
        fd_set read_set;
        FD_ZERO(&read_set);
        memcpy(&read_set, &base_set, sizeof(base_set));

        int max_fd = socket_fd;
        for(int i = 0; i < n_clients; i++){
            if(client_fds[i] > max_fd)
                max_fd = client_fds[i];
        }

        ret_check = select(100, &read_set, NULL, NULL, NULL);
        CHECK_ERROR(ret_check < 0, "select", NULL);

        // 2. 处理新链接, accept并添加到client_fds
        if(FD_ISSET(socket_fd, &read_set)){
            // 接受客户端连接
            struct sockaddr_in client_addr;
            socklen_t addr_len = sizeof(client_addr);

            // 新链接
            int new_fd = accept(socket_fd, (struct sockaddr*)&client_addr, &addr_len);

            // 新链接处理
            if(new_fd < 0){
                perror("accept");
            }
            else if(n_clients < MAX_CLIENTS){
                printf("New client from %s:%d (fd=%d)\n", 
                       inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port), new_fd);
                client_fds[n_clients++] = new_fd;
                FD_SET(new_fd, &base_set);
            }
            else{
                close(new_fd);
                printf("Max clients reached!\n");
            }
        }

        // 3. 处理客户端消息
        for(int i = 0; i < n_clients; i++){
            int client_fd = client_fds[i];

            if (FD_ISSET(client_fd, &read_set)) {
                char buf[BUF_SIZE];
                ssize_t len = recv(client_fd, buf, sizeof(buf) - 1, 0); // 保留空间给'\0'

                // 3.1 用户已断开链接
                if (len <= 0) {
                    printf("Client %d disconnected\n", client_fds[i]);

                    FD_CLR(client_fd, &base_set);   
                    close(client_fds[i]);
                    for(int k = i; k < n_clients; k++){
                        client_fds[k] = client_fds[k + 1];
                    }

                    n_clients--;
                    i--;
                }
                // 3.2 写文件并回复
                else{
                    buf[len] = '\0';
                    printf("From client[fd=%d]:\n%.*s\n", client_fds[i], (int)len, buf);

                    // 3.2.1 将收到的内容写到文件
                    int file_fd = open("receive_massages.log", O_WRONLY | O_CREAT | O_APPEND, 0644);
                    if(file_fd >= 0){
                        char timestamp[64];
                        time_t now = time(NULL);
                        struct tm *tm_info = localtime(&now);
                        strftime(timestamp, sizeof(timestamp), "[%Y-%m-%d %H:%M:%S]", tm_info);
                        char filtered[len + 1];
                        for(int i = 0; i < len; i++){
                            filtered[i] = (buf[i] == '\r' || buf[i] == '\n') ? ' ' : buf[i];
                        }
                        filtered[len] = '\0';

                        dprintf(file_fd, "%s [fd:%d]", timestamp, client_fds[i]);
                        write(file_fd, filtered, len);
                        write(file_fd, "\n", 1);
                        close(file_fd);
                    }
                    else{
                        perror("open log file failed");
                    }

                    // 3.2.2 回复报文
                    int dev_id = get_device_id_from_request(buf);
                    switch(dev_id) {
                    case 0: 
                        ret_check = send_http_response(client_fds[i], "text/plain", "To STM32: Message received and logged");
                        CHECK_ERROR(ret_check < 0, "Fail to send_http_response", NULL);
                        break;
                    case 1:
                    default:    // default是测试用
                        ret_check = send_log(client_fds[i]);
                        CHECK_ERROR(ret_check < 0, "send_log failed", NULL);

                        FD_CLR(client_fd, &base_set);
                        close(client_fds[i]);
                        for(int k = i; k < n_clients; k++){
                            client_fds[k] = client_fds[k + 1];
                        }

                        n_clients--;
                        i--;
                        break;
                    case 2:
                        ret_check = clear_log(client_fds[i]);
                        CHECK_ERROR(ret_check < 0, "send_log failed", NULL);
                        
                        FD_CLR(client_fd, &base_set);
                        close(client_fds[i]);
                        for(int k = i; k < n_clients; k++){
                            client_fds[k] = client_fds[k + 1];
                        }

                        n_clients--;
                        i--;

                        break;
                    }
                }
            }
        }
    }

    // 清理
    for(int i = 0; i < n_clients; i++){
        if(client_fds[i] > 0){
            close(client_fds[i]);
        }
    }
    close(socket_fd);
    return 0;
}

// ============== 函数实现 ==============
int send_http_response(int fd, const char *content_type, const char *content) {
    char body[BUF_SIZE];
    snprintf(body, sizeof(body),
    "HTTP/1.1 200 OK\r\n\r\n[\"%s\"]\n",
//            "HTTP/1.1 200 OK\r\n\r\n\"%s\"\n", 
             content);

    int ret_check = send(fd, body, strlen(body), 0);
    CHECK_ERROR(ret_check < 0, "Failed to send_http_response", NULL);

    return 0;
}

int get_device_id_from_request(const char*http_request){
    // 1. 查找路径的位置
    const char *path_start = strstr(http_request, "GET /");
    if (!path_start) return -1;

    // 2. 定位数字位置
    const char* num_ptr = path_start + 5;   // "跳过GET /"
    if(!isdigit(*num_ptr)) return -1;

    // 3. 转换ASCII数字为整型
    return *num_ptr - '0';
}

int send_log(int client_fd){
    // 1. 打开文件
    FILE *file = fopen(LOG_FILE, "r");
    CHECK_ERROR(!file, "Failed to open log file", send_http_response(client_fd, "text/plain", "Error reading logs"));

    // 2. 存储符合条件的行
    char line_buf[BUF_SIZE] = {0};

    // 3. 读取数据
    while (fgets(line_buf, sizeof(line_buf), file)) {
        // 直接发送当前行
        if (strstr(line_buf, "GET /0")){
            send_http_response(client_fd, "text/plain", line_buf);         
            usleep(10 * 1000);
        }
    }

    // 4.关闭文件
    fclose(file);
    
    return 0;
}

int clear_log(int client_fd){
    // 1. 打开文件
    int ret_check = truncate(LOG_FILE, 0);
    if(ret_check == 0){
        send_http_response(client_fd, "text/plain", "Logs cleared (truncate)\n");
    }
    else{
        perror("Clear failed");
    }

    return 0;
}

